<template>
  <div style="padding: 20px;padding-top: 0;">
    <HuilanBasicToolbar style="margin-top: 20px">
      <el-button type="success" size="small" @click.stop="plugAdd">新增分类
      </el-button>
      <el-button type="warning" size="small" @click="ImportAggregate">
        导入分类
      </el-button>
      <el-button type="primary" size="small" :loading="exportCategoryLoading" @click="exportCategory">
        导出分类
      </el-button>
      <el-button type="" size="small" :loading="multipleDelLoading" @click="multipleDel">
        删除分类
      </el-button>
    </HuilanBasicToolbar>
    <HuilanBasicSearchbar :model="searchForm" :fields="searchFieldList" @reset="searchReset" @search="searchChange">
    </HuilanBasicSearchbar>
    <avue-crud v-model="form" :option="option" :data="treeData" ref="crud" @row-save="rowSave" @row-update="rowUpdate"
      @row-del="rowDel" @selection-change="selectionChange" :page.sync="page" @current-change="currentChange"
      @size-change="sizeChange" @select-all="handleSelectAll">
      <template v-slot:menu="scope">
        <HuilanBasicActionTool :actions="getRowActions(scope.row)"
          @command="handleRowCommand($event, scope.row, scope.index)" />
      </template>
      <template #classifyName="{ row }">
        <span>{{ row.classifyName }}</span>
      </template>
    </avue-crud>
    <QSGDrawer :title="dataInTitle" :fullscreen="false" :size="600" append-to-body :visible.sync="trainingRecordsVisible"
      :wrapperClosable="false" :before-close="beforeClose">
      <avue-form :option="optionForm" ref="form" v-model="form" :upload-preview="uploadPreview" @submit="submit"
        :upload-before="uploadBefore" :upload-after="uploadAfter">
        <template slot="aggregateText">
          <span>请先 <a :href="downUrl" download><span style="color: #409eff">下载模板</span></a>，填写完成后上传（支持xls、xlsx格式文件）</span>
        </template>
      </avue-form>
      <template v-slot:footer>
        <el-button size="small" type="primary" @click.stop="formSave">确 定</el-button>
        <el-button size="small" @click.stop="formClose">取 消</el-button>
      </template>
    </QSGDrawer>
  </div>
</template>
<script>
import QSGDrawer from "@/components/QSGDrawer/index";
import { baseURL } from "@/api/common";
import { aiClassifyManageList, aiClassifyManageSave, aiClassifyManageDelete, aiClassifyManageUpdate, aiClassifyManageTree, aiClassifyManageExport } from "@/api/configure/intelligentClassification";
import serviceList from '@/config/serviceList'
const { ai } = serviceList
export default {
  name: "classificationMg",
  components: {
    QSGDrawer,
  },
  props: {
  },
  data() {
    return {
      parentId: '',
      form: {},
      dataInTitle: '导入分类',
      trainingRecordsVisible: false,
      exportCategoryLoading: false,
      treeData: [],
      selectionList: [],
      downUrl: `${baseURL}template/智能分类导入模板.xlsx`,
      multipleDelLoading: false,
      selecteds: true,
      rowData: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      searchForm: {
        classifyName: "",
      },
      searchFieldList: [
        {
          prop: "classifyName",
          placeholder: "请输入分类名称",
        },
      ],
      data: [
      ],
      option: {
        tip: false,
        align: 'center',
        border: true,
        index: false,
        rowKey: 'id',
        rowParentKey: 'parentId',
        editBtn: false,
        delBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogWidth: "40%",
        dialogType: "drawer",
        dialogCustomClass: "huilan-drawer-form",
        selection: true,
        updateBtnIcon: ' ',
        cancelBtnIcon: ' ',
        saveBtnIcon: ' ',
        addBtnIcon: ' ',
        defaultExpandAll: false,
        headerAlign: "left",
        props: {
          children: "childrenList",
          // 设置了value后getNode才能通过key获取节点
        },
        column: [
          {
            label: '上级分类',
            prop: 'parentId',
            type: 'tree',
            span: 24,
            hide: true,
            disabled: false,
            clearable: true,
            defaultExpandAll: true,
            align: 'left',

            props: {
              label: "classifyName",
              // children: "childrenList",
              // 设置了value后getNode才能通过key获取节点
              value: "id",
            },
            dicData: [
              // {
              //   label: '字典1',
              //   value: 0,
              //   children: [{
              //     label: '字典3',
              //     value: 2
              //   }]
              // }, {
              //   label: '字典2',
              //   value: 1
              // }
            ],
            rules: [
              {
                required: true,
                message: '请选择上级分类',
                trigger: "blur",
              },
            ],
          },
          {
            label: '分类名称',
            prop: 'classifyName',
            span: 24,
            maxlength: 20,
            showWordLimit: true,
            align: 'left',
            rules: [
              {
                required: true,
                message: '请输入分类名称',
                trigger: "blur",
              },
              {
                min: 1,
                max: 100,
                message: "长度在 1 到 20 个字符",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      optionForm: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 90,
        updateBtnIcon: ' ',
        cancelBtnIcon: ' ',
        saveBtnIcon: ' ',
        addBtnIcon: ' ',
        column: [
          {
            label: '',
            prop: 'aggregateText',
            span: 24,
            labelWidth: 0,
          },
          {
            label: '',
            prop: 'file',
            dataType: 'object',
            type: 'upload',
            labelWidth: 0,
            propsHttp: {
              res: 'data'
            },
            data: {
              classifyId: '',
            },
            accept: ".xls,.xlsx",
            span: 24,
            action: `${baseURL}api/${ai}/aiClassifyManage/import`,
            tip: '上传文件大小不超过30M',
            fileSize: 30 * 1024,
            rules: [
              {
                required: true,
                message: '请上传',
                trigger: "blur",
              },
            ],
          },
        ]
      },
    }
  },
  watch: {

  },
  computed: {

  },
  mounted() {
  },
  methods: {
    getRowActions() {
      const list = [];
      const btnList = [
        {
          name: '查看',
          command: 'showView',
          auth: 'VIEW'
        },
        {
          name: '编辑',
          command: 'showEdit',
          auth: 'UPDATE',
        },
        {
          name: '删除',
          command: 'remove',
          auth: 'DEL',
        },
        {
          name: '新增子分类',
          command: 'childAdd',
          auth: 'ADDCHILD',
        }
      ];
      btnList.forEach(item => {
        if (item.auth) {
          list.push({
            name: item.name,
            command: item.command
          });
        }
      });
      return list;
    },
    handleRowCommand(command, row, index) {
      const self = this;
      const excelFileColumn = this.findObject(this.option.column, "parentId");
      switch (command) {
        case 'showView':
          self.$refs.crud.rowView(row, index);
          break;
        case 'showEdit':
          excelFileColumn.disabled = true
          if (row.level === 1) {
            self.form.parentId = row.parentId
          } else {
            self.form.parentId = row.id
          }
          self.$refs.crud.rowEdit(row, index);
          break;
        case 'remove':
          self.rowDel(row);
          break;
        case 'childAdd':
          self.childAdd(row, index);
          break;
      }
    },
    childAdd(row, index) {
      this.form.parentId = row.id
      const excelFileColumn = this.findObject(this.option.column, "parentId");
      excelFileColumn.disabled = true
      this.$refs.crud.rowAdd(row, index);
      this.rowData = row
    },
    rowDel(row) {
      this.publicDel(row.id)
    },
    searchChange() {
      // this.query = { ...this.searchForm };
      // this.page.currentPage = 1;
      // this.treeLoad(this.page, this.query);
      this.page.currentPage = 1
      if (this.searchForm.classifyName) {
        this.treeList(this.classifyId, 'serach')
      } else {
        this.treeList(this.classifyId)
      }
    },
    searchReset() {
      this.searchForm = {};
      this.page.currentPage = 1;
      this.treeList(this.classifyId)
    },
    plugAdd() {
      this.$refs.crud.rowAdd();
      const excelFileColumn = this.findObject(this.option.column, "parentId");
      excelFileColumn.disabled = false
    },
    formClose() {
      debugger
      if (this.$refs.form) {
        this.$refs.form.resetForm()
      }
      this.trainingRecordsVisible = false
    },
    treeList(classifyId, type) {
      const self = this
      const params = {
        current: this.page.currentPage,
        size: this.page.pageSize,
        ...this.searchForm,
      }
      aiClassifyManageList({ ...params, classifyId }).then(res => {
        const data = res.data.data || []
        if (data.length !== 0) {
          self.treeData = data.records
          self.page.total = data.total
          // 展开树结构的子节点
          if (type === 'add') {
            setTimeout(() => {
              self.$refs.crud.toggleRowExpansion(self.rowData, true)
            }, 500);
          }
          if (type === 'serach') {
            self.treeData.map(v => {
              self.$refs.crud.toggleRowExpansion(v, true)
              if (v.children && v.children.length > 0) {
                self.searchExtenceRecursion(v.children)
              }
            })
          }
        } else {
          self.treeData = []
        }
      })
    },
    recursion(childrenList) {
      childrenList.forEach(item => {
        // item['label'] = item['classifyName
        if (item.childrenList && item.childrenList.length > 0) {
          this.recursion(item.childrenList)
        } else {
          item.childrenList = []
        }
      })
    },
    searchExtenceRecursion(childrenList) {
      childrenList.forEach(item => {
        this.$refs.crud.toggleRowExpansion(item, true)
        if (item.children && item.children.length > 0) {
          this.searchExtenceRecursion(item.children)
        }
      })
    },
    rowSave(row, done) {
      const self = this
      let parentId = ''
      if (row.parentId === '-1') {
        parentId = '0'
      } else {
        parentId = row.parentId
      }
      const params = {
        ...row,
        parentId,
        classifyId: this.classifyId,
      }
      aiClassifyManageSave(params).then(res => {
        if (res.data.success) {
          self.$message.success('保存成功')
          self.treeList(self.classifyId, 'add')
          self.formTree(self.classifyId)
          // 展开树结构的子节点
          // this.$refs.crud.setCurrentRow(form)

        }
      }).catch(() => {
        done()
      })
      done()
    },
    ImportAggregate() {
      const self = this
      this.dataInTitle = '导入分类'
      this.trainingRecordsVisible = true
      setTimeout(() => {
        self.$refs.form.resetForm()
      }, 500);
    },
    rowUpdate(row, index, done) { // eslint-disable-line
      aiClassifyManageUpdate({ ...row }).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.treeList(this.classifyId)
          this.formTree(this.classifyId)
          this.formClose()
        }
        done()
      }).catch(() => {
        done()
      })
    },
    selectionChange(list) {
      this.selectionList = list
    },
    multipleDel() {
      if (this.selectionList.length > 0) {
        const ids = this.selectionList.map(item => item.id).join(',')
        this.publicDel(ids)
      } else {
        this.$message.error('请选择要删除的数据')
        return
      }
    },
    publicDel(ids) {
      this.$confirm(this.$t("aicosCommon.mutiDeleteConfirmTip"), {
        confirmButtonText: this.$t("aicosCommon.confirmBtn"),
        cancelButtonText: this.$t("aicosCommon.cancelBtn"),
        type: "warning",
      })
        .then(() => {
          this.multipleDelLoading = true
          return aiClassifyManageDelete({ ids });
        })
        .then(() => {
          this.$message({
            type: "success",
            message: this.$t("aicosCommon.successOperate"),
          });
          this.multipleDelLoading = false
          // 数据回调进行刷新
          this.treeList(this.classifyId)
          this.formTree(this.classifyId)
        });
    },
    formTree(classifyId) {
      aiClassifyManageTree({ classifyId }).then(res => {
        const excelFileColumn = this.findObject(this.option.column, "parentId");
        const data = [{
          classifyName: '分类管理',
          id: '0',
          children: []
        }]
        if (res.data.data && res.data.data.length > 0) {
          data[0].children = res.data.data
          excelFileColumn.dicData = [{
            classifyName: '分类管理',
            id: '0',
            children: res.data.data
          }]
        } else {
          excelFileColumn.dicData = [{
            classifyName: '分类管理',
            id: '0',
            children: []
          }]
        }
      })
    },
    init(classifyId) {
      this.page.currentPage = 1
      this.page.pageSize = 10
      // this.treeList(classifyId)
      this.formTree(classifyId)
      this.classifyId = classifyId
      this.searchReset()
    },
    exportCategory() {
      let ids = ''
      if (this.selectionList.length > 0) {
        ids = this.selectionList.map(item => item.id).join(',')
      }
      this.exportCategoryLoading = true
      aiClassifyManageExport({ classifyId: this.classifyId, ids }).then(res => {
        if (res.status === 200) {
          const data = res.data;
          let fileName = ''
          if (res.headers['content-disposition']) {
            fileName = res.headers['content-disposition'].split(';')[1].split('filename=')[1];
            //将fileName解码
            const fileNameDecode = decodeURIComponent(fileName);
            this.downFile(data, fileNameDecode);
            this.$message({
              type: "success",
              message: "导出成功",
            })
          } else {
            this.$message({
              type: "error",
              message: "导出失败",
            })
          }
        }
        this.exportCategoryLoading = false
      }).catch((err) => {
        console.log(err)
        this.exportCategoryLoading = false
      })
    },
    uploadBefore(file, done, loading) {  // eslint-disable-line
      const excelFileColumn = this.findObject(this.optionForm.column, "file");
      excelFileColumn.data.classifyId = this.classifyId;
      if (file.name.indexOf('.xls') === -1 && file.name.indexOf('.xlsx') === -1) {
        this.$message.error('请上传xls、xlsx格式文件')
        loading()
        return false
      }
      setTimeout(() => {
        done();
      }, 1000);
    },
    uploadAfter(res, done) {
      if (res) {
        this.$message.success(res)
        this.trainingRecordsVisible = false
        this.treeList(this.classifyId)
        setTimeout(() => {
          this.$refs.form.resetForm()
        }, 500);
      } else {
        this.$message.error(res)
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.treeList(this.classifyId)
    },
    sizeChange(pageSize) {
      this.page.size = pageSize;
      this.page.currentPage = 1
      this.treeList(this.classifyId)
    },
    handleSelectAll() {
      const list = this.$refs.crud.data
      list.map(v => {
        this.$refs.crud.toggleRowSelection(v, this.selecteds)
        if (v.children && v.children.length > 0) {
          this.recursive(v.children, this.selecteds)
        }
      })
      this.selecteds = !this.selecteds
    },
    recursive(list, flug) {
      list.map(v => {
        this.$refs.crud.toggleRowSelection(v, flug)
        if (v.children && v.children.length > 0) {
          this.recursive(v.children, flug)
        }
      })
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ .avue-crud__menu {
  min-height: 0;
}
</style>
